from django.shortcuts import render, redirect, reverse
from .models import User
from course.models import Purchase

# Create your views here.

def detail_handler(req):
    if req.method == 'POST':
        req.user.nikname = req.POST.get('nikname','')
        req.user.gender = req.POST.get('gender', 'M')
        req.user.save()
    return render(req, 'user_data.html')

def login_handler(req):
    if req.method == 'GET':
        return redirect(reverse('index'))
    try:
        u = User.objects.get(username = req.POST['account'])
        if u.password == req.POST['password']:
            req.session['user'] = u.id
    except Exception as e:
        return render(req, 'index.html', context={'login_err':'Wrong Username or Password'})
    return redirect(reverse('user_detail'))


def register_handler(req):
    if req.method == 'GET':
        return redirect(reverse('index'))
    username = req.POST['account']
    password = req.POST['password']

    try:
        u = User.objects.get(username = username)
        if  u.password == password:
            # log it in 
            req.session['user'] = u.id
            return redirect(reverse('user_detail',  args=[u.id]))
        else: 
            return redirect(reverse('index'))
    except Exception as e:
        pass

    # register
    u = User(username = username, password = password)
    u.save()
    req.session['user'] = u.id
    return redirect(reverse('user_detail'))


def logout_handler(req):
    req.session.flush()
    return redirect(reverse('index'))


def cart_handler(req):
    b = Purchase.objects.filter(user = req.user, state = 'CT')
    return render(req,'user_shoppingcart.html', context={'bought': b})


def bought_handler(req):
    b = Purchase.objects.filter(user = req.user, state = 'PD')
    return render(req,'user_course.html', context={'bought': b})